<template>
  <div class="hello">
    <button @click="setCount">{{ count }}</button>
    <h1>{{ msg }}</h1>
    <hello :msg="msg" />
    <input type="text" v-model="todo" />
    <ul>
      <li v-for="(item, index) in list" :key="index">{{ item }}</li>
    </ul>
    <button class="addTodo" @click="addItem">{{ count }}</button>
    <button class="loadUser" @click="loadUser">loadUser</button>
    <p v-if="user.loading" class="loading">Loading</p>
    <div v-else class="userName">{{ user.data && user.data.username }}</div>
    <p v-if="user.error" class="error">Error!</p>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from "vue";
import axios from "axios";
import Hello from "./Hello.vue";

export default defineComponent({
  name: "hello-world",
  components: {
    Hello,
  },
  props: {
    msg: String,
  },
  emits: ["send"],
  setup(props, { emit }) {
    const todo = ref("");
    const count = ref(1);
    const list = ref<string[]>([]);
    const user = reactive({
      data: null as any,
      loading: false,
      error: false,
    });
    const setCount = () => {
      count.value++;
    };
    const loadUser = () => {
      user.loading = true;
      axios
        .get("https://jsonplaceholder.typicode.com/users/1")
        .then((resp) => {
          user.data = resp.data;
        })
        .catch(() => {
          user.error = true;
        })
        .finally(() => {
          user.loading = false;
        });
    };
    const addItem = () => {
      if (todo.value) {
        list.value.push(todo.value);
        emit("send", todo.value);
      }
    };
    return {
      count,
      list,
      setCount,
      addItem,
      todo,
      user,
      loadUser,
    };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
